package com.ch3cooh.serviceuser.user.service;

import com.ch3cooh.common.exception.OhBuyException;
import com.ch3cooh.serviceuser.tool.IdGenerator;
import com.ch3cooh.serviceuser.tool.RedisLock;
import com.ch3cooh.serviceuser.user.entity.User;
import com.ch3cooh.serviceuser.user.entity.UserElement;
import com.ch3cooh.serviceuser.user.repository.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @功能: 用户service
 * @作者:chanson
 * @时间:2018/5/24 22:00
 */
@Service("userService")
@Slf4j
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    StringRedisTemplate redisTemplate;

    private static  IdGenerator idGenerator = new IdGenerator(1L,1L);

    /**
     * 用户登录
     * @param user
     * @return
     */
    public UserElement login(User user) {
        User userFromDb = userMapper.selectByEmail(user.getEmail());
        if(userFromDb == null) throw new OhBuyException("用户不存在");
        boolean isMatched = passwordEncoder.matches(user.getPassword(), userFromDb.getPassword());
        if( !isMatched ) throw new OhBuyException("密码错误");
        return User.toUe(userFromDb);
    }

    /**
     * 用户注册
     * @param user
     */
    public void register(User user) {
        //创建redis分布式锁
        String lockKey = user.getEmail();
        RedisLock lock = new RedisLock(redisTemplate, lockKey);
        try {
            if (lock.lockWithoutTimeout()) {
                User userFromDb = userMapper.selectByEmail(user.getEmail());
                if (userFromDb != null) throw new OhBuyException("该邮箱已被注册");
                //若数据库中没有该注册邮箱
                user.setUuid(idGenerator.genId());
                //设置 MD5密码
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                user.setNickname("欧拜用户:" + user.getEmail());
                userMapper.insert(user);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info(String.format("用户(%s)注册出现异常，已释放redisLock" , user.getEmail()));
            throw new RuntimeException(e.getMessage());
        }finally {
            lock.unlock();
        }




    }
}
